<template>
	<div class="layoutWnd" v-show="visible" @mouseleave="visible = false">
		<ul :style="{ width: wndWidth + 'px' }">
			<LayoutCell
				v-for="(val, idx) in cellNumber"
				:key="idx"
				:posX="getPosX(idx)"
				:posY="getPosY(idx)"
				@hovercells="onHoverCells"
				@layout="onLayout"
			/>
		</ul>
	</div>
</template>

<script setup name="LayoutWnd">
import { ref, computed, onMounted, reactive } from "vue";
import LayoutCell from "./LayoutCell.vue";

const emit = defineEmits(["layout"]);
const visible = ref(false);
const layoutHtml = ref("");
const layout = reactive({ row: 0, col: 0 });

const wndWidth = computed(() => {
	return 45 * config.layoutWnd.col + 5;
});

const cellNumber = computed(() => {
	return config.layoutWnd.row * config.layoutWnd.col;
});

const getPosX = idx => {
	return Math.floor(idx % config.layoutWnd.col) + 1;
};
const getPosY = idx => {
	return Math.floor(idx / config.layoutWnd.col) + 1;
};
const getHtml = () => {
	if (config.layoutWnd == null) {
		config.layoutWnd = { row: 5, col: 5 };
	}

	if (config.layoutWnd.row < 5) config.layoutWnd.row = 5;
	if (config.layoutWnd.col < 5) config.layoutWnd.col = 5;

	const rwidth = 45 * config.layoutWnd.col + 5;

	let html = '<ul style="width:' + rwidth + 'px">';
	let sq;
	for (let i = 0; i < config.layoutWnd.row; i++) {
		for (let j = 0; j < config.layoutWnd.col; j++) {
			sq = `<li id="li_${i + 1}_${j + 1}"><span>${i + 1}X${j + 1}</span></li>`;
			html += sq;
		}
	}

	html += "</ul>";
	return html;
};
// const HideWnd = () => {
// 	this.$bus.$emit("showlayoutwnd", false);
// };

const onHoverCells = (r, c) => {
	for (let i = 0; i < config.layoutWnd.row; i++) {
		for (let j = 0; j < config.layoutWnd.col; j++) {
			const liid = "li_" + (i + 1) + "_" + (j + 1);
			const elli = document.getElementById(liid);
			if (i < r && j < c) {
				elli.style.backgroundColor = "#B4B4B4";
			} else {
				elli.style.backgroundColor = "#828282";
			}
		}
	}
};

const onLayout = (r, c) => {
	layout.row = r;
	layout.col = c;
	visible.value = false;
	emit("layout", r, c);
};

const show = () => {
	visible.value = true;
};

defineExpose({
	show
});

onMounted(() => {
	layoutHtml.value = getHtml();

	// this.$bus.$on("hightlightcells", (r, c) => {
	// 	for (let i = 0; i < config.layoutWnd.row; i++) {
	// 		for (let j = 0; j < config.layoutWnd.col; j++) {
	// 			const liid = "li_" + (i + 1) + "_" + (j + 1);
	// 			const elli = document.getElementById(liid);
	// 			if (i < r && j < c) {
	// 				elli.style.backgroundColor = "#B4B4B4";
	// 			} else {
	// 				elli.style.backgroundColor = "#828282";
	// 			}
	// 		}
	// 	}
	// });
});
</script>

<style scoped>
.layoutWnd {
	position: absolute;
	background-color: #5a5a5a;
	z-index: 20;
}

.layoutWnd ul {
	padding: 5px 0px 0px 5px;
	width: 230px;
}
</style>
